package com.app.activitys.adapters;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.util.ByteArrayBuffer;

import com.app.activitys.ActivityMenu;
import com.app.activitys.ActivityProblemaInternet;
import com.app.activitys.Faixas;
import com.app.entidades.Album;
import com.app.entidades.Coletania;
import com.app.entidades.Musicas;
import com.app.webservice.MusicaRest;
import com.example.applucianokikao.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class AdapterColetania extends ArrayAdapter<Coletania>{

	private List<Coletania> coletanias;
	private int layoutResourceId;
	private Context contexto;
	private Handler handler = new Handler();
	private AlertDialog dialog;

	public AdapterColetania(Context context, int resource,
			List<Coletania> objects) {
		super(context, resource, objects);
		contexto = context;
		coletanias = objects;
		layoutResourceId = resource;
	}

	@Override 
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		RecordHolder holder = null;
		final Coletania cole = coletanias.get(position);
		
		if (row == null) { 
			LayoutInflater inflater = ((Activity) contexto).getLayoutInflater();
			row = inflater.inflate(layoutResourceId, parent, false);
			holder = new RecordHolder();
			holder.txtTitle = (TextView) row.findViewById(R.id.txt_nome_banda);
			holder.imageItem = (ImageView) row.findViewById(R.id.button_banda); 
			row.setTag(holder);
		} else {
				holder = (RecordHolder) row.getTag();
		}
		
		holder.txtTitle.setText(cole.getTitulo());
		
		Bitmap m = buscaImagem(nomeImagem(cole.getCapa()));
		
		if(m==null){
			// baixa a imagem e salva no celular
			baixaImagem(cole.getCapa());
			holder.imageItem.setImageResource(R.drawable.foto_banda_padrao);
			//button_image.setImageResource(R.drawable.foto_banda_padrao);
			//ai buscamos de novo
		}else{
			holder.imageItem.setImageBitmap(m);
			//button_image.setImageBitmap(m);
		}
		//
		holder.imageItem.setAdjustViewBounds(true);
		holder.imageItem.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final String pastaBanda = cole.getPasta();
				
				AsyncTask<Void, Void,List<Musicas>> task = new AsyncTask<Void,Void,List<Musicas>>(){

					@Override
					protected List<Musicas> doInBackground(Void... params) {
						MusicaRest rest = new MusicaRest();
						List<Musicas> musicas = new ArrayList<Musicas>();
						
						try {
							musicas = rest.getListaMusicasColetania(pastaBanda);
						}catch (Exception e) {
							Intent intent = new Intent(contexto, ActivityProblemaInternet.class);
							contexto.startActivity(intent);
							this.cancel(true);
						}
						return musicas;
					}
					
					@Override
			        protected void onPostExecute(List<Musicas> result) {
						Toast.makeText(contexto, "Listando Musicas", Toast.LENGTH_SHORT).show();
						Bundle bundle = new Bundle();
						bundle.putSerializable("musicas", (Serializable)result);
						Intent intent = new Intent(contexto, Faixas.class);
						intent.putExtra("mus", bundle);
						contexto.startActivity(intent);
					}
				
				};
				task.execute();
	
			}
		});
		
		return row;
	} 
	
	static class RecordHolder {
		TextView txtTitle;
		ImageView imageItem;
	}

	private void baixaImagem(final String url) {
	      System.out.println("baixando");
			new Thread(new Runnable() {	
				@Override
				public void run() {
				        try {
				        	URL aURL = new URL(url);
						    URLConnection conn = aURL.openConnection();
						    conn.connect();
						        
						    
						    InputStream is = conn.getInputStream();
						    final BufferedInputStream bis = new BufferedInputStream(is);
						    
						    String nome = nomeImagem(url);
						    
						    ContentValues values = new ContentValues(3);
						    values.put(Media.DISPLAY_NAME, nome);
						    values.put(Media.DESCRIPTION, "Imagem bandas");
						    values.put(Media.MIME_TYPE, "image/jpeg");
						    
						    File file = new File(Environment.getExternalStorageDirectory()+"/Kikao/");

						    
						    FileOutputStream fos = new FileOutputStream(file+"/"+nome);
						    
						    // fos= (FileOutputStream) contexto.getContentResolver().openOutputStream(Uri);
						    fos.write(getBytes(bis));
						    fos.flush();
						    fos.close();
						    System.out.println("Baixou e Salvou");
						    bis.close();
						    is.close();
					   } catch (IOException e) {
						      Log.e("ImagemButton", "Error getting bitmap", e);
					   }
				}
	    	}).start();
	    }
		
		private Bitmap buscaImagem(String nomeImagem){
			Bitmap bmp=null;
				
			    File file = new File(Environment.getExternalStorageDirectory()+"/Kikao/"+nomeImagem);
			    if(file.exists()){
			    	System.out.println("existe");
			    	bmp = BitmapFactory.decodeFile(file.getPath());
			    }else{
			    	System.out.println("não existe");
			    }
				return bmp;
			
		}
		
		private String nomeImagem(String link){
			String[] valores = link.split("/");
			return valores[valores.length-1];
		}
		
		
		public byte[] getBytes(BufferedInputStream bis){
			ByteArrayBuffer baf = new ByteArrayBuffer(50);

			int count = 0;

			try {
				while((count = bis.read()) != -1){
					baf.append((byte) count);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return baf.toByteArray();
		}
		
		private void gerarToast(CharSequence message) {
			Toast.makeText(contexto, message,Toast.LENGTH_SHORT).show();
		}

}
